package com.ruoyi.flowable.controller;

import org.flowable.common.engine.api.FlowableException;
import org.flowable.common.engine.api.FlowableObjectNotFoundException;
import org.flowable.engine.IdentityService;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.idm.api.Group;
import org.flowable.idm.api.User;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;


/**
 * 流程控制
 *
 * @author Hack2003
 * @date 2024/3/15 11:23
 **/
@RestController
@RequestMapping("/test")
public class MyTestController {
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;
    @Autowired
    private IdentityService identityService;
    /**
     * 部署流程
     */
    @PostMapping("/testDeploy")
    public String deployProcess() {
        Deployment deployment = repositoryService.createDeployment()
                .addClasspathResource("flow_d3rx5tz6.bpmn20.xml")
                .name("部署名称版本信息")
                .deploy();
        return "success"+deployment.getId();
    }

    /**
     * 部署删除
     */
    @DeleteMapping("/delDeploy")
    public String delDeploy(String deploymentId) {
        try {
            //要删除的部署ID以及级联删除该部署相关的所有流程实现、任务、历史数据等
            repositoryService.deleteDeployment(deploymentId, true);
            return ("部署[" + deploymentId + "]删除成功");
        }catch (FlowableObjectNotFoundException e){
            return ("部署[" + deploymentId + "]不存在，删除失败");
        }
    }

    /**
     * 根据部署ID,获取流程定义ID列表。一次部署可以部署多个文件会产生多个流程定义ID
     */
    @GetMapping("/getDefList")
    public String getDefList(String deploymentId) {
        try {
            List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).list();
            return ("该部署ID的流程定义ID=[" + list + "]");
        }catch (FlowableObjectNotFoundException e){
            return ("根据部署ID[" + deploymentId + "]获取流程定义不存在");
        }
    }

    /**
     * 启动流程
     */
    @PostMapping("/startProcess")
    public String startProcess(String processDefinitionId) {
        try {
            Map<String,Object> variables = new HashMap<>(0);
            ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinitionId, variables);
            return "流程启动成功"+processInstance.getProcessDefinitionId();
        }catch (FlowableException e){
            return ("流程启动失败：" + e.getMessage());
        }
    }
    /**
     * 获取运行中的任务
     */
    @GetMapping("/getTaskRunList")
    public List<Task> getTaskRunList() {
        List<Task> list = taskService.createTaskQuery().list();
        return list;
    }

    /**
     * 任务拾取
     */
    @GetMapping("/getRunTaskByPerson")
    public String getRunTaskByPerson() {
        Task task = taskService.createTaskQuery().taskId("105055").taskCandidateUser("1").singleResult();
        if(Objects.nonNull(task)){
            taskService.claim(task.getId(),"1");
            return "拾取成功"+task.getProcessDefinitionId();
        }else{
            return "任务未找到";
        }

    }
    /**
     * 任务退还
     */
    @GetMapping("/getRunTaskClearPerson")
    public String getRunTaskClearPerson() {
        Task task = taskService.createTaskQuery().taskId("105055").taskAssignee("1").singleResult();
        if(Objects.nonNull(task)){
            taskService.unclaim(task.getId());
            return "任务退还:"+task.getAssignee();
        }else{
            return "任务未找到";
        }
    }
    /**
     * 任务交接
     */
    @GetMapping("/getTaskRunChgPerson")
    public String getTaskRunChgPerson() {
        Task task = taskService.createTaskQuery().taskId("105055").taskAssignee("1").singleResult();
        if(Objects.nonNull(task)){
            taskService.setAssignee(task.getId(),"1");
            return "任务交接:"+task.getAssignee();
        }else{
            return "任务未找到";
        }
    }


    /**
     * 添加组
     */
    @GetMapping("/addGroup")
    public String addGroup() {
        Group group = identityService.newGroup("1");
        group.setName("admin组");
        group.setType("可选组类型1");
        identityService.saveGroup(group);
        Group group2 = identityService.newGroup("2");
        group2.setName("comm组");
        group2.setType("可选组类型2");
        identityService.saveGroup(group2);
        return "添加组成功";
    }
    /**
     * 添加用户
     */
    @GetMapping("/addUser")
    public String addUser() {
        User user = identityService.newUser("1");
        user.setDisplayName("it管理员");
        user.setFirstName("admin");
        identityService.saveUser(user);
        User user2 = identityService.newUser("2");
        user2.setDisplayName("主管");
        user2.setFirstName("ry");
        identityService.saveUser(user2);
        User user3 = identityService.newUser("3");
        user3.setDisplayName("老板");
        user3.setFirstName("boss");
        identityService.saveUser(user3);
        return "添加用户成功";
    }
    /**
     * 分配用户到组
     */
    @GetMapping("/getTaskRunChgPersonGroup")
    public String getTaskRunChgPersonGroup() {
        //将用户加入到组
        identityService.createMembership("1", "1");
        identityService.createMembership("2", "2");
        identityService.createMembership("3", "2");

        //将组作为侯选人组添加到任务中
        taskService.addCandidateGroup("110018","1");
        taskService.addCandidateGroup("110018","2");

        return "完成用户组添加";
    }
    /**
     * 任务拾取组用户
     */
    @GetMapping("/getRunTaskByPersonGroup")
    public String getRunTaskByPersonGroup() {
        Task task = taskService.createTaskQuery().taskId("110018").taskCandidateGroup("1").taskCandidateUser("1").singleResult();
        if(Objects.nonNull(task)){
            taskService.claim(task.getId(),"1");
            return "拾取成功"+task.getProcessDefinitionId();
        }else{
            return "任务未找到";
        }

    }
    /**
     * 完成任务
     */
    @PostMapping("/completeTask")
    public String completeTask(String taskId) {
        try {
            // 获取流程实例ID
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                    .processInstanceId(taskService.createTaskQuery().taskId(taskId).singleResult().getProcessInstanceId())
                    .singleResult();

            Map<String,Object> variables = new HashMap<>(0);
            variables.put("outcome","拒绝");
            taskService.complete(taskId,variables);


            // 查询流程实例下的下一个待办任务
            Task nextTask = taskService.createTaskQuery()
                    .processInstanceId(processInstance.getId())
                    .orderByTaskCreateTime().desc() // 可根据实际需求排序
                    .active() // 活动任务
                    .singleResult(); // 获取第一个活动任务

            if (nextTask != null) {
                return ("下个任务ID=["+nextTask.getId()+"]");
            } else {
                return "已经没有任务了";
            }
        }catch (FlowableObjectNotFoundException e){
            return ("未找到指定的任务["+taskId+"]");
        }
    }
}
